package club.itstudio.IContainer.service;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.HashSet;

@Service
public class ServerPortService {

    private HashSet<Integer> portSet = new HashSet<>();

    public int getRandomServerPort() {
        try {
            while (true) {
                int port = new ServerSocket(0).getLocalPort();
                if (port == 0) return 0;
                while (portSet.contains(port)) {
                    continue;
                }
                portSet.add(port);
                return port;
            }
        }catch (IOException e) {
            return 0;
        }
    }

    public void releasePort(int port) {
        portSet.remove(port);
    }
}
